import store from '../store/index.js'
import {getHeaderSysInfo} from '@/common/common.js'
import config from '@/common/config.js'
const {baseUrl}= config
let waitList=[]
let loadingList=[]
const errorCode=[300002,300007,300008]
const extraCode=[900000]
const fetch=(config)=>{
	return new Promise((resolve,reject)=>{
		let token = uni.getStorageSync('token') || 'noToken'
		const {url,method,data,header,loading}=config
		const uaStr=getHeaderSysInfo()
		let isShowLoading=true
		let text='加载中...'
		if(typeof loading ==='boolean'){
			isShowLoading=loading
		}else if(typeof loading==='object'){
			isShowLoading=loading.isShow
			text=loading.text||''
		}
		if(isShowLoading){
			loadingList.push(loading)
			uni.showLoading({
				title:text
			})
		}
		uni.request({
			url:baseUrl+url,
			method:method||'POST',
			data:data?data:{},
			header:{
				...header,
				AUTHORIZATION:token,
				UA:uaStr
			},
			success(res){
				console.log('请求成功:',res,`url:${url}`,`参数:${data?JSON.stringify(data):'无'}`)
				resolve(res)
			},
			fail(res){
				console.log('请求错误:',res,`url:${url}`,`参数:${data?JSON.stringify(data):'无'}`)
				reject(res)
				throw res
			},
			complete(){
				if(isShowLoading){
					loadingList.pop()
					if(loadingList.length===0){
						uni.hideLoading()
					}
				}
			}
		})
	})
}
const reLogin=async()=>{
	await store.dispatch('login')
	for(let i=0;i<waitList.length;i++){
		const {config,resolve,reject}=waitList[i]
		fetch(config).then(res=>{
			const {code,msg,data}=res.data
			if(code!==0){
				if(extraCode.indexOf(code)===-1){
					uni.showToast({
						icon:'none',
						title: msg|| '服务器开小差了~请稍后再试'
					})
					reject(res.data)
					throw res.data
				}else{
					reject(res.data)
				}
			}
			resolve(data,res)
		},res=>{
			uni.showToast({
				icon:'none',
				title: '服务器开小差了~请稍后再试'
			})
			reject(res)
			throw res.data
		})
		waitList.splice(i,1,'')
	}
	waitList=[]
}

const createFetch=(method)=>{
	return async(url,data,params={})=>{
		let token = uni.getStorageSync('token') || 'noToken'
		let header =params.header||{}
		let loading =params.loading
		return new Promise((resolve,reject)=>{
			const config={method,url,data,header,loading}
			fetch(config).then(res=>{
				const {code,msg,data}=res.data
				if(errorCode.indexOf(code)!==-1){
					waitList.push({config,resolve,reject})
					if(waitList.length===1){
						uni.removeStorageSync('token')
						reLogin()
					}
					return
				}
				if(code!==0){
					if(extraCode.indexOf(code)===-1){
						uni.showToast({
							icon:'none',
							title: msg|| '服务器开小差了~请稍后再试'
						})
						reject(res.data)
						throw res.data
					}else{
						reject(res.data)
					}
				}
				resolve(data,res)
			},
			res=>{
				reject(res)
				uni.showToast({
					icon:'none',
					title: '服务器开小差了~请稍后再试'
				})
				throw res.data
			})
		}) 
	}
	
}

export const post= createFetch('POST')
export const get= createFetch('GET')